package com.hdj.chapter4;

import net.sf.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 * @auther hdj
 * @date 2017/12/12.
 */
public class Builder {
    private OrderState orderState = new OrderState();
    private static final BeanCopier COPIER = BeanCopier.create(OrderState.class,Order.class,false);
    private class OrderState{
        private String code;
        private List<String> offers;
        private Map<String,Object> features;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public List<String> getOffers() {
            return offers;
        }

        public void setOffers(List<String> offers) {
            this.offers = offers;
        }

        public Map<String, Object> getFeatures() {
            return features;
        }

        public void setFeatures(Map<String, Object> features) {
            this.features = features;
        }
    }

    public Builder code(String code){
        orderState.code = code;
        return this;
    }

    public Builder offer(String offer){
        if(orderState.offers == null) {
            orderState.offers = new ArrayList<String>();
        }
        orderState.offers.add(offer);
        return this;
    }

    public Builder offers(List<String> offers){
        orderState.offers = offers;
        return this;
    }

    public <T> Builder feature(String key, T obj){
        if(orderState.features == null) {
            orderState.features = new HashMap<String,Object>();
        }
        orderState.features.put(key,obj);
        return this;
    }

    public Builder features(Map<String,Object> features){
        orderState.features = features;
        return this;
    }

    public Order build(){
        Order order = new Order();
        COPIER.copy(orderState,order,null);
        orderState = null;
        return order;
    }
}
